package com.sdp.wx.controller;


import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.wx.cache.clean.WxCleanCache;
import com.sdp.wx.db.wx_vendor_info.entity.WxVendorInfo;
import com.sdp.wx.db.wx_vendor_info.service.IWxVendorInfoService;
import com.sdp.wx.utils.WxConstants;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/WxVendorInfoController")
public class WxVendorInfoController {

	@Autowired
	private IWxVendorInfoService iWxVendorInfoService;
	
	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private WxCleanCache wxCleanCache;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iWxVendorInfoService, WxVendorInfo.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody WxVendorInfo wxVendorInfo) {
		if(wxVendorInfo==null) {
			return Result.error("供应商信息为空");
		}
		if(StringUtils.isEmpty(wxVendorInfo.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iWxVendorInfoService, WxVendorInfo.class, new String[] {"vendorCode","vendorName"}, "keyId", wxVendorInfo, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("供应商编号和名称不能重复");
			}
			wxVendorInfo.setIsUse(WxConstants.是.getCode());
			wxVendorInfo.setCreateTime(LocalDateTime.now());
			iWxVendorInfoService.save(wxVendorInfo);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iWxVendorInfoService, WxVendorInfo.class, new String[] {"vendorCode","vendorName"}, "keyId", null, wxVendorInfo, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("供应商编号和名称不能重复");
			}
			
			iWxVendorInfoService.updateById(wxVendorInfo);
		}
		wxCleanCache.cleanVendorCache();
		return Result.ok();
	}
	
}

